package vos.vn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WebService_GetJSONActivity extends Activity {
    private  HttpURLConnection conn;
    private URL url;
    private InputStreamReader in;
    private OutputStreamWriter out;
    private String token;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
         setContentView(R.layout.main);       
         
         login("black","123123");         
         TextView tv = new TextView(this);    
         List<String> values = this.getAllDicData(getJSON(), "ItemsCount");
         String text ="";
         for(String s: values) {
        	 text+=s;
         }
         tv.setText(text);
         setContentView(tv);
    }
    
    /**
     * @param src source string. It is not null
     * @param key key to find. 
     * @return the first value of key in dictionary
     */
    public String getDicData(String src, String key) {
		//check source
    	if(src == null)
    		return null;
    	
    	//get beginIndex
    	int index = src.indexOf(key);
    	if(index == -1)
    		return null;
    	else
    		index += key.length() + 2; // {"[string]":
    	
    	//get value data
    	StringBuilder sb = new StringBuilder();
    	if(src.charAt(index)!='"')
    		sb.append(src.charAt(index));
    	else
    		index++;    	
    	while( src.charAt(index)!='"' && src.charAt(index)!=',' && src.charAt(index)!='}')  {    		
    	    sb.append(src.charAt(index++));    		
    	}
    	
    	return sb.toString();
    }
    
    /**
     * @param src the dictionary which will be used. It is not null
     * @param key the key to search
     * @return a list which archives all values are appropriate with the key 
     */
    public List<String> getAllDicData(String src, String key) {
    	List<String> values = new ArrayList<String>();
    	
    	//check source
    	if(src == null)
    		return null;
    	
    	//get beginIndex
    	int index = src.indexOf(key);
    	if(index == -1)
    		return null;
    	else
    		index += key.length() + 2; // string":
  
    	int len = src.length();  	
    	String s = "";
    	while(index < len) {    		    		
	    	if( src.charAt(index)!='"' && src.charAt(index)!=',' &&
	    			src.charAt(index)!='}' &&src.charAt(index)!='{'&& 
	    			src.charAt(index)!=':' && src.charAt(index)!=']'&& 
	    			src.charAt(index)!='[' )  {    		
	    	    s += src.charAt(index++);    		
	    	} else {
	    		if(!s.equals("")) {
	    			values.add(s);
	    			String sub = src.substring(index);
	    			index += sub.indexOf(key) + key.length();
	    		}	    			
	    		s="";
	    		index++;
	    	}	    	
    	}
    	
    	return values;
    }
    
    /**
     * @param uid
     * @param pass
     * @return
     */
    public boolean login(String uid, String pass) {
    	StringBuilder sb = new StringBuilder("");
    	String address = "http://www.littleemperors.com/json/Login.aspx";	
    	boolean result = false;	
    	
    	try {
    	    url = new URL(address);
    	    conn = (HttpURLConnection) url.openConnection();      	    
    	    String datNearhere = "UserName="+uid+"&Password="+pass;
    	    
    	    //properties for outputing
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");           
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Content-length",""+ datNearhere.length());
            
            //get data
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(datNearhere);            
            out.flush();
            out.close();                       
            in = new InputStreamReader(conn.getInputStream());
            BufferedReader buff = new BufferedReader(in);
            String line;
            do {
                line = buff.readLine();
                sb.append(line);
            } while (line != null);            
    	    if(getDicData(sb.toString(), "IsSuccessful").equals("true")) {
    	    	//fuck expected:"Token="
    	    	token ="Token=" + getDicData(sb.toString(), "Token");
    	    	result = true;
    	    }
    	   
    	} catch(MalformedURLException mEX) {
    		
    	} catch(IOException ioEX) {
    		
    	} finally {
    		try {
    		    url = null;
    		    conn.disconnect();
    		}catch(Exception e) {
    			
    		}
    	}    
    	return result;
    }
    
    /**
     * @return get string which expresses all data from web service.
     * This is in JSON syntax
     */
    public String getJSON() {    	
    	TextView tv = new TextView(this);          
        StringBuilder sb = new StringBuilder();
        String tErrorString = "";                   
        
        try{  
            url = new URL("http://www.littleemperors.com/json/GetCategories.aspx");  
            
            //open connection to server url
            conn = (HttpURLConnection) url.openConnection();
  
            //properties for outputing
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            //conn.setRequestProperty("Connection", "Keep-Alive");
            //conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Accept:", "application/json");  
            conn.setRequestProperty("Content-length",""+ token.length());            
                   
            //get data 
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(token);            
            out.flush();
            out.close();           
            
            in = new InputStreamReader(conn.getInputStream());
            BufferedReader buff = new BufferedReader(in);
            String line;
            do {
                line = buff.readLine();
                sb.append(line + "\n");
            } while (line != null);
            
        } catch (Exception e) {  
            tErrorString = e.getMessage();  
        } finally {
        	conn.disconnect();
        }
          
        if(!tErrorString.equals(""))
        	tv.setText(tErrorString);
        else
        	tv.setText(sb.toString());
        
        setContentView(tv);  
        
    	return sb.toString();
    }   
}